var createError = require('http-errors');
var express = require('express');
var path = require('path');
var logger = require('morgan');
const cors = require("cors")
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var articleRouter = require('./routes/article');
var likeRouter = require('./routes/like');
var UploadRouter = require('./routes/upload');
const cookieParser = require('cookie-parser');
var app = express();

const corsoption = {
  // origin: 'http://localhost:5173',//只允许这个特定的源
  origin: ['http://localhost:5173', 'http://localhost:5174'],//允许多个个特定的源
  optionsSuccessStatus: 200
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors(corsoption))
app.use(cookieParser());

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/article', articleRouter);
app.use('/like', likeRouter);
app.use('/upload-img', UploadRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// app.all("*", (req, res, next) => {
//   //设置允许跨域的域名，*代表允许任意域名跨域
//   res.header("Access-Control-Allow-Origin", "http://127.0.0.1:5173");
// })
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
